var util = require('../../utils/util.js')
// 递归多图上传
function imageUpload(data, formData,_this) {

  // 不上传图片
  if (data.path.length == 0){
    submitSendMail(formData, _this); // 搞起
    return;
  }
 
  var that = this,
  i = data.i ? data.i : 0,
  success = data.success ? data.success : 0,
  fail = data.fail ? data.fail : 0;
  var reslust = "";
  wx.uploadFile({
    url: data.url,
    filePath: data.path[i],
    name: 'imageFile', //这里根据自己的实际情况改
    formData: {
      folderName: formData.folderName,
      mudid: formData.mudid
    },
    header: { "Content-Type": "multipart/form-data" },
    success: (resp) => {
      console.log("resp=>", resp);
      reslust = JSON.parse(resp.data)
      // reslust = resp.data;
      if (reslust.status) success++;
      console.log(i);
      //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
    },
    fail: (res) => {
      fail++;
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: () => {
      console.log(i);
      i++;
      if (i == data.path.length) { //当图片传完时，停止调用          
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
        console.log("当图片传完时，停止调用")
        submitSendMail(formData, _this); // 搞起
      } else { //若图片还没有传完，则继续调用函数
        console.log(i);
        data.i = i;
        data.success = success;
        data.fail = fail;
        that.imageUpload(data, formData,_this);
      }
    }
  });
}

// reslust:递归后结果;formData:传输数据对象;_this:feedback.js对象
function submitSendMail(formData, _this) {
  _this.setData({
    disabled: true
  });
  wx.request({
    url: formData.submitSendMailUrl, //仅为示例，并非真实的接口地址
    data: formData,
    success: function(res) {
      var status = res.data.status;
      if (status) {
        wx.showModal({
          title: '提示',
          content: '发送成功',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '../index/index'
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              wx.navigateTo({
                url: '../index/index'
              })
            }
          }
        })
      } else {
        wx.showModal({
          title: '发送失败',
          content: '请联系管理员!',
        })
      }
    },fail:function(){
      wx.showModal({
        title: '发送失败',
        content: '请联系管理员!',
      })
      wx.hideToast();
      _this.setData({
        hidden: true,
        disabled: false
      });
    },
    complete:function(){
      wx.hideToast();
      _this.setData({
        hidden: true,
        disabled: false
      });
    }
  })
}

module.exports = { 
  imageUpload: imageUpload
};